﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Collections;
using SchoolLibrary;
using SchoolLibrary.DataBase.Builder.Factory;
using SchoolLibrary.DataBase.Builder;
using SchoolLibrary.Entity;
using SchoolLibrary.DataBase.Connect;

namespace SchoolLibrary.DataBase.DAO.Helper
{
    public class DAOHelper<T> where T : Identity
    {
        public List<T> getResultList(Query query)
        {
            return getResultList(query.QueryString);
        }

        public List<T> getResultList(string query)
        {
            Connection connection = ConnectionFactory.getConnection();
            connection.Open();
            DataTable table = connection.executeSelect(query);
            connection.Close();

            List<T> objects = new List<T>();
            AbstractEntityBuilder builder = EntityBuilderFactory.getBuilder(typeof(T));
            foreach (DataRow row in table.Rows)
            {
                Identity entity = builder.Build(row);
                objects.Add((T)entity);
            }
            return objects;
        }

        public T getSingleResult(Query query)
        {
            return getSingleResult(query.QueryString);          
        }

        public T getSingleResult(string query)
        {
            List<T> objects = getResultList(query);
            if (objects.Count > 0)
            {
                return objects[0];
            }
            else
            {
                return null;
            }
        }

        public void executeUpdate(Query query)
        {
            Connection connection = ConnectionFactory.getConnection();
            connection.Open();
            connection.executeUpdate(query.QueryString);
            connection.Close();
        }

        public long getLastId(string tableName)
        {
            Query query = new Query(Identity.SELECT_LAST_ID);
            query.setStringParameter("tableName", tableName);
            T entity = getSingleResult(query);
            return entity.Id;
        }
    }
}
